<template>
    <div class="setting">
        <div class="setting-container">
            <div style="display: flex;justify-content: space-between;align-items: center;">
                <div style="color: #000000;font-weight: bold;" class="s-20">系统设置</div>
                <div @click="goback"  class="back">
                    <img  src="../../../assets/img/person/back.png" alt="">
                    <span class="s-15 pointer">返回</span>
                </div>
            </div>
            <div style="margin-top: 20px;">
                <span class="label s-16">输入时启动系统软键盘</span>
                <el-switch
                    v-model="arouseKeyboard"
                    @change="settingArouseKeyboard"
                    active-text="开"
                    inactive-text="关"
                    active-color="#0085FF"
                    inactive-color="#C0C4CC"
                    >
                </el-switch>
            </div>
            <div style="margin-top: 36px;">
                <span class="label s-16">课件启动方式</span>
                <el-select v-model="teachingMode" style="width: 120px;" @change="changeMode" >
                    <el-option v-for="item in modeOptions" :key="item.value" :label="item.lable" :value="item.value"></el-option>
                </el-select>
            </div>
            <div style="margin-top: 36px;">
                <span class="s-16">缓存文件 :</span>
                <span style="padding-left: 5px;">{{cacheSize + 'M'}}</span>
                <button class="cleanBtn" @click="clean">清除缓存</button>
            </div>
            <div style="margin-top: 36px;">
                <span class="s-16">版本信息 : </span>
                <span style="padding-left: 5px;">{{version}}</span>
                <button class="checkVersionBtn" @click="checkUpdate">检查更新</button>
            </div>
        </div>
    </div>
</template>

<script>
var totalSize = 0
import { SqlLibBook } from "../../../../../../static/lib/sqlite/service/SqlLibBook";
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser'
import { getAppNewVersion } from '@/content/api/appversion'
import { UpdateApp } from '../../../utils/UpdateApp'
export default {
    name: 'setting',
    data () {
        return {
            arouseKeyboard: localStorage.getItem('arouse') === 'true' ,
            teachingMode:localStorage.getItem('teachMode') || '1',
            modeOptions:[{
                lable:'本地模式',
                value:'1',
            },{
                lable:'在线模式',
                value:'2',
            }],
            version:'',
            cacheSize:localStorage.getItem('totalCacheSize') || 0,
        }
    },
    created(){
        this.checkCacheSize()
    },
    mounted () {
        this.version = this.$readIniFile('data', 'versionInfo')
    },
    methods: {
        goback () {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let user = SqlLibUser.queryCurrentUser(sqlLib)
            let obj = {
                bookId: user.bookId
            }
            if (this.authorzation) {
                if (user.lessonId) {
                    obj.lessonId = user.lessonId
                } else {
                    let book = SqlLibBook.queryChapterLessonByBookId(sqlLib, user.bookId)
                    if (book) {
                        obj.lessonId = book[0].lessonVO[0].id
                    }
                }
            }
            this.$router.push({ name: 'home', params: this.authorzation ? obj : {} })
        },
        settingArouseKeyboard (val) {
            console.log(val);
            localStorage.setItem('arouse', val)
        },
        changeMode(mode){
            localStorage.setItem('teachMode', mode)
        },
        clean(){
            let rescDir = window.$DATADIR + '/resc';
            deleteFile(rescDir, '.zip');
            localStorage.setItem('totalCacheSize', 0 )
            this.cacheSize = 0
            window.$Vue.$message({
                message: '下载缓存清除完成',
                center: true,
                type: 'success'
            });
        },
        async checkUpdate() {
            // 调用接口获取最新版本号，并与当前版本比较
            let oldVersion = this.$readIniFile('data', 'ver')
            console.log(oldVersion);
            let res = await getAppNewVersion({
                clientType: '1',
                currentVersion:oldVersion,
            })
            let data = res.returnValue
            if (res.code !== '0') {
                this.$message.error('检查更新失败，请稍后重试')
            }
            if (oldVersion === data.currentVersion) {
                this.$message.success('您当前已是最新版本')
                return
            }
            if (oldVersion < data.currentVersion) {
                const path = require('path')
                let exePath = process.env.NODE_ENV === 'production' ? path.resolve(path.dirname(process.execPath), 'bos_updater.exe') : './bos_updater/bin/bos_updater'
                let exeParmsArr = [data.url, data.isGlobal === '0' ? '/e' : '/z', '']
                UpdateApp.update(exePath, exeParmsArr, { message: data.description, version: data.currentVersion, close: false, cancel: '取消', }, false);
            }else{
                this.$message.success('您当前已是最新版本')
            }

        },
        checkCacheSize(){
            if (localStorage.getItem('totalCacheSize')) {
                totalSize = 0
            }
            let rescDir = window.$DATADIR + '/resc';
            this.calcSizeSync(rescDir, '.zip');
        },
        calcSizeSync(dirPath,extname){
            let _this = this
            let fs = require('fs');
            let path = require('path');
            var files = [];
            if (fs.existsSync(dirPath)) {
                files = fs.readdirSync(dirPath);
                files.forEach(function (file, index) {
                    var curPath = dirPath + "/" + file;
                    if (fs.statSync(curPath).isDirectory()) {
                        _this.calcSizeSync(curPath, '.zip');
                    } else {
                        if (path.extname(curPath) === extname) {
                            fs.stat(curPath,(err,data)=>{
                                totalSize = totalSize+data.size
                                localStorage.setItem('totalCacheSize', (totalSize/1024/1024).toFixed(1) )
                                _this.cacheSize = (totalSize/1024/1024).toFixed(1)
                                console.log('totalSize',totalSize);
                            })
                        }
                    }
                });
            }
        },
    }
}
// 递归删除特定后缀的文件
function deleteFile(dirPath, extname) {
    let fs = require('fs');
    let path = require('path');
    var files = [];
    if (fs.existsSync(dirPath)) {
        files = fs.readdirSync(dirPath);
        files.forEach(function (file, index) {
            var curPath = dirPath + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                deleteFile(curPath, extname);
            } else {
                if (path.extname(curPath) === extname) {
                    fs.unlinkSync(curPath);
                }
            }
        });
    }
}
// function calcSizeSync(dirPath,extname){
//     let fs = require('fs');
//     let path = require('path');
//     var files = [];
//     if (fs.existsSync(dirPath)) {
//         files = fs.readdirSync(dirPath);
//         files.forEach(function (file, index) {
//             var curPath = dirPath + "/" + file;
//             if (fs.statSync(curPath).isDirectory()) {
//                 calcSizeSync(curPath, extname);
//             } else {
//                 if (path.extname(curPath) === extname) {
//                     fs.stat(curPath,(err,data)=>{
//                         console.log('data' , data);
//                         totalSize = totalSize+data.size
//                         localStorage.setItem('totalCacheSize', (totalSize/1024/1024).toFixed(1) )
//                         console.log('totalSize',totalSize);
//                     })
//                 }
//             }
//         });
//     }
// }

</script>

<style lang="scss" scope>
.setting {
    width: 100%;
    height: 100%;
    .setting-container {
        width: 100%;
        padding: 20px 30px;
        color: #606266;
        .back {
            cursor: pointer;
            width: 88px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #0085FF;
            color: #FFFFFF;
            border-radius: 4px;
            border: 1px solid #D7D7D7;
            img{
                width: 8px;
                height: 11px;
                margin-right: 6px;
            }
        }
    }
    .label {
        color: #606266;
        padding-right: 20px;
    }
    .cleanBtn , .checkVersionBtn{
        width:88px ;
        height: 32px;
        background: #FAFAFA;
        outline: none;
        border: 1px solid #D7D7D7;
        border-radius: 4px;
        color: #303133;
        margin-left: 10px;
        cursor: pointer;
    }
    .cleanBtn:hover{
        color: #fff;
        background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);
    }
    .checkVersionBtn:hover{
        color: #fff;
        background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);
    }
}
</style>